package com.wbs.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wbs.api.ItemAPI;
import com.wbs.model.TbItem;
import com.wbs.service.CartService;
import com.wbs.vo.CartVO;
import com.wbs.vo.DetailVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Author: 芝梦
 * @Description:
 * @DateTime: 2024/2/26 19:43
 */
@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ItemAPI itemAPI;

    //增加购物车
    @Override
    public void addCart(Long skuId, Integer num, String id) {
        //1. 从redis中取出当前用户的购物车列表
        List<Object> cartVOS = getRedis(id);
        List<CartVO> cartVOList = cartVOS.stream()
                .map(x -> JSONObject.parseObject(JSON.toJSONString(x), CartVO.class))
                .collect(Collectors.toList());

        //1.1 根据skuid查询商品信息
        TbItem tbItem = itemAPI.selectBySkuId(skuId);
        String seller = tbItem.getSeller();

        //2. 判断是否购买过当前商家的产品
        CartVO carts = null;
        int subscript = 0;
        for (int i = 0; i < cartVOList.size(); i++) {
            if (cartVOList.get(i).getSeller().equals(seller)) {
                carts = cartVOList.get(i);
                subscript = i;
                break;
            }
        }

        //3. 没有购买过, 创建购物车并且把商品存入进去
        if (carts == null) {
            //创建购物车
            CartVO cart = new CartVO();
            cart.setSeller(seller);

            //创建购物车明细
            ArrayList<DetailVO> detailVOS = new ArrayList<>();
            //创建具体商品详情
            DetailVO detailVO = new DetailVO();
            detailVO.setItemId(tbItem.getId());
            detailVO.setNum(num);
            detailVO.setPrice(tbItem.getPrice());
            detailVO.setPicPath(tbItem.getImage());
            detailVO.setGoodsId(tbItem.getGoodsId());
            detailVO.setSellerId(tbItem.getSeller());
            detailVO.setTitle(tbItem.getTitle());
            detailVO.setTotalFee(new BigDecimal(detailVO.getNum() + "").multiply(tbItem.getPrice()));
            detailVOS.add(detailVO);

            //将商品信息添加到购物车对象中
            cart.setDetailVOS(detailVOS);

            //将购物车对象添加到购物车列表中
            cartVOList.add(cart);
        } else {
            //4. 买过, 判断是否购买过当前商家的同类型的商品
            List<DetailVO> detailVOS = carts.getDetailVOS();
            DetailVO dv = null;
            for (DetailVO detailVO : detailVOS) {
                if (detailVO.getItemId().equals(skuId)) {
                    dv = detailVO;
                }
            }
            //5. 没有买过, 在商品列中后追加一条记录
            if (dv == null) {
                DetailVO detailVO = new DetailVO();
                detailVO.setItemId(tbItem.getId());
                detailVO.setNum(num);
                detailVO.setPrice(tbItem.getPrice());
                detailVO.setPicPath(tbItem.getImage());
                detailVO.setGoodsId(tbItem.getGoodsId());
                detailVO.setSellerId(tbItem.getSeller());
                detailVO.setTitle(tbItem.getTitle());
                detailVO.setTotalFee(new BigDecimal(detailVO.getNum() + "").multiply(tbItem.getPrice()));
                //存入detailVOS
                detailVOS.add(detailVO);

                //更新cartVOS原有数据
                carts.setDetailVOS(detailVOS);
                cartVOList.set(subscript, carts);
            } else {
                //6. 买过, 修改当前商品的数量和小计
                dv.setNum(dv.getNum() + num);
                dv.setTotalFee(new BigDecimal(dv.getNum()).multiply(dv.getPrice()));
                //判断 num为0时 从集合中移除
                if (dv.getNum() <= 0) {
                    detailVOS.remove(dv);
                }
                //判断 集合为空时 移除 List<DetailVO> 集合
                if (detailVOS.size() <= 0) {
                    cartVOList.remove(carts);
                }
            }
        }

        //7. 把新的购物车信息存入到redis中
        redisTemplate.boundHashOps("cartList").put(id, cartVOList);
    }


    public List<Object> getRedis(String userId) {
        List<Object> o = (List<Object>) redisTemplate.boundHashOps("cartList").get(userId);
        //carVOS null
        if (o == null) {
            o = new ArrayList<>();
        }

        return o;
    }

    //查询购物车
    @Override
    public List<CartVO> getCart(String id) {
        List<Object> cartList = getRedis(id);
        String jsonString = JSONObject.toJSONString(cartList);
        List<CartVO> cartVOS = JSONObject.parseArray(jsonString, CartVO.class);
        return cartVOS;
    }

    //清除购物车信息
    @Override
    public void clearCatList(String id) {
        redisTemplate.boundHashOps("cartList").delete((String) id);
    }
}
